package cn.hxzy.icon.icon.service.impl;

import cn.hxzy.icon.icon.entity.Resource;
import cn.hxzy.icon.icon.entity.Role;
import cn.hxzy.icon.icon.repository.RoleRepository;
import cn.hxzy.icon.icon.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * 实现
 *
 * @author little black
 */
@Service("roleService")
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleRepository roleRepository;

    /**
     * 添加对象
     *
     * @param role
     * @return
     */
    @Override
    public void add(Role role) {
        roleRepository.save(role);
    }

    /**
     * 删除对象
     *
     * @param id
     * @return
     */
    @Override
    public void deleteById(Integer id) {
        roleRepository.deleteById(id);
    }

    /**
     * 修改对象
     *
     * @param role
     * @return
     */
    @Override
    public void update(Role role) {
//      查找id
        Optional<Role> byId = roleRepository.findById(role.getId());
//        id存在的话
        if (byId.isPresent()) {
//            只写入id对应的resource
            role.setResourceList(byId.get().getResourceList());
        }
        roleRepository.save(role);
    }

    /**
     * @return
     */
    @Override
    public List<Role> findAll() {
        List<Role> all = roleRepository.findAll();
        return all;
    }

    /**
     * @param id
     * @return
     */
    @Override
    public Role FindById(Integer id) {
        Optional<Role> byId = roleRepository.findById(id);
        if (byId.isPresent()) {
            return byId.get();
        }
        return null;
    }

    @Override
    public void authorize(Integer roleId, Integer resourceId) {
        Optional<Role> byId = roleRepository.findById(roleId);
        if (byId.isPresent()) {
            Role role = byId.get();
            List<Resource> resourceList = role.getResourceList();
            boolean flag=false;
            for (int i = 0; i < resourceList.size(); i++) {
                if (resourceList.get(i).getId().equals(resourceId)){
                    flag=true;
                    resourceList.remove(i);
                }
            }
            if (!flag){    //未找到
                Resource resource = new Resource();
                resource.setId(resourceId);
                resourceList.add(resource);
            }
            roleRepository.save(role);
        }
    }
}
